﻿using System;
using Microsoft.Office.Interop.Outlook;

namespace Office.Utility.Toolbar
{
    public class CommandBarEventArgs : EventArgs
    {
        private readonly Inspector _inspector;
        private readonly Explorer _explorer;
        private readonly Microsoft.Office.Core.CommandBar _bar;

        public Inspector Inspector
        {
            get { return _inspector; }
        }

        public Explorer Explorer
        {
            get { return _explorer; }
        }

        public Microsoft.Office.Core.CommandBar CommandBar
        {
            get { return _bar; }
        }

        public ItemAdapter CurrentItem
        {
            get
            {
                if (_explorer != null)
                {
                    try
                    {
                        return _explorer.Selection.Count != 1 ? null : ItemAdapter.FromObject(_explorer.Selection[1]);
                    }
                        //In some cases, _explorer.Selection throws a COM exception.
                        //In those cases, there is no valid selection, so return null
                    catch (System.Runtime.InteropServices.COMException)
                    {
                        return null;
                    }
                }

                if (_inspector != null)
                    return ItemAdapter.FromObject(_inspector.CurrentItem);

                throw new ApplicationException("only one of _explorer or _inspector can be null");
            }
        }

        internal CommandBarEventArgs(WindowAdapter window, Microsoft.Office.Core.CommandBar bar)
        {
            _bar = bar;

            if (window.Explorer != null)
                _explorer = window.Explorer;
            else if (window.Inspector != null)
                _inspector = window.Inspector;
            else
                throw new ApplicationException("Invalid WindowAdapter passed to CommandBarEventArgs");
        }
    }
}